import { configureStore, combineReducers } from '@reduxjs/toolkit';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import logger from 'redux-logger';
import { setupListeners } from '@reduxjs/toolkit/dist/query/react';
import {
  MiddlewareAPI,
  isRejectedWithValue,
  Middleware,
} from '@reduxjs/toolkit';

import postsApi from './posts';
import userApi from './user';

const persistConfig = {
  key: 'root',
  storage,
};
const rootReducer = combineReducers({
  [postsApi.reducerPath]: postsApi.reducer,
});
const persistedReducer = persistReducer(persistConfig, rootReducer);

// 自定义错误中间件
const rtkQueryErrorLogger: Middleware =
  (api: MiddlewareAPI) => (next) => (action) => {
    // RTK Query uses `createAsyncThunk` from redux-toolkit under the hood, so we're able to utilize these use matchers!
    if (isRejectedWithValue(action)) {
      console.warn('We got a rejected action!');
      // toast.warn({ title: 'Async error!', message: action.error.data.message });
    }

    return next(action);
  };
// 中间件集合
const middlewareHandler = (getDefaultMiddleware: any) => {
  const middlewareList = [
    ...getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: ['persist/PERSIST'],
      },
    }),
    // api中间件
    postsApi.middleware,
    userApi.middleware,
    rtkQueryErrorLogger,
  ];
  if (process.env.NODE_ENV === 'development') {
    middlewareList.push(logger);
  }
  return middlewareList;
};
//API slice会包含自动生成的redux reducer和一个自定义中间件
export const rootStore = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) => middlewareHandler(getDefaultMiddleware),
});

export const persistor = persistStore(rootStore);
export type RootState = ReturnType<typeof rootStore.getState>;

setupListeners(rootStore.dispatch);
